<?php
/*
*	Kleophatra - Open Source Content Management System
*	------------------------------------------------------------------------
*	Copyright (C) 2007-2010, Sergio Milardovich <smilardovich@yahoo.com.ar>
*	This program is Free Software.
*
*	@package	Kleophatra
*	@subpackage	/lib
*	@license	http://www.gnu.org/copyleft/gpl.html GNU/GPL License 2.0
*	@author		Sergio Milardovich <smilardovich@yahoo.com.ar>
*	@link		http://www.kleophatra.org
*	@author		Matías Parodi <mparodilabs@gmail.com>
*	@link		http://mparodi.com
*/
class kleotemplate extends kleocore {
	
/*
	// DEPRECATED VALUES...
	var $start_title = '::';
	var $end_title = '::';
	var $start_subtitle = '(';
	var $end_subtitle = ')';
	var $title_separator = '|';
	var $template_file = 'test.tpl';
	var $start_replace_pattern = '{';
	var $end_replace_pattern = '}';
	var $cachedir = 'cache';
*/	
	// Custom fields var
	var $customs;
	// Loading the file...
	function tpl_load($file, &$buff, $cache=false, $search=false){
		if(!file_exists($file)){
			$this->search_tpl($file,$path,$search);
		} else {
			$path = $file;
		}
		if(!$cache){
				$buff = file_get_contents($path);
				$this->make_includes($buff, $buff);
		} else {
			$this->apploadlib(KLEO_LIB_DIR.'cache.lib.php', 'kleocache', $cache);
			$cache->cache_start($file,$buff);
			$this->make_includes($buff, $buff);
			$cache->cache_end(file_get_contents($path));
		}
		if(!isset($buff)){
			$this->apperror('('.$file.')'.L_TEMPLATE_ERROR, 'common');
		}
	}

	function php_load($file, &$buff){
		ob_start();
 		$buff = require($file);
		$buff = ob_get_contents();
		ob_end_clean();
	}

	
	// The 'main' template.lib.php function...
	function tpl_set($pattern, $replace, $buff, &$buff){
		if(!is_array($pattern)){
			$buff = preg_replace("/{".$pattern."}/", $replace, $buff);			
		} else {
 			foreach($pattern as $key => $value) {
   				$buff = preg_replace("/{".$key."}/", $value, $buff);
			}
		}
	
	}


    // Making <a> <-- it's very possible that you will not use this function...
    // We made it just for fun :-p
    function make_links($buff, &$buff) {
        if(preg_match_all('/(?:\{=link\((.*),(array\((?:.+)\))\)\})/U', $buff, $matches, PREG_SET_ORDER)){
            for ($i=0; $i<count($matches); $i++) {
                $return = '<a href="' . strtolower($matches[$i][1]) . '" ';
                eval('$attributes = ' . $matches[$i][2] . ';');
                foreach ($attributes as $key => $value) {
                    if ($key == 'caption') {
                        if (!empty($value)) {
                            $return .= '>' . $value . '</a>';
                        } else { $this->apperror(L_INSERT_A_CAPTION_FOR_ARRAY, "common"); }
                    } else {
                        $return .= $key . '="' . $value . '"';
                    }
                }
                $buff = str_replace($matches[$i][0], $return, $buff);
            }
        }

    }

	// Conditionals (if) functions
	function make_conditionals($buff, &$buff){
		if(preg_match_all('|<!--\s*if\s*\((.+)\)\s*-->(.*)<!--\s*endif\s*-->|Uis', $buff, $matches, PREG_SET_ORDER)){
		  $i=0;
		  foreach($matches as $match){
			$clauses = explode(" ",$match[1]);
			$conditional_buff = null;
			switch($clauses[1]){
				case '==':
				if(eval("return ".$clauses[0].";") == eval("return ".$clauses[2].";")){
					$conditional_buff = $match[2];
				}
				break;
				case '!==':
				if(eval("return ".$clauses[0].";") !== eval("return ".$clauses[2].";")){
					$conditional_buff = $match[2];
				}
				break;
				case '>':
				if(eval("return ".$clauses[0].";") > eval("return ".$clauses[2].";")){
					$conditional_buff = $match[2];
				}
				break;
				case '<':
				if(eval("return ".$clauses[0].";") < eval("return ".$clauses[2].";")){
					$conditional_buff = $match[2];
				}
				break;
				case '<=':
				if(eval("return ".$clauses[0].";") <= eval("return ".$clauses[2].";")){
					$conditional_buff = $match[2];
				}
				break;
				case '>=':
				if(eval("return ".$clauses[0].";") >= eval("return ".$clauses[2].";")){
					$conditional_buff = $match[2];
				}
				break;
		      }


			$buff = str_replace($matches[$i][0],$conditional_buff,$buff);
			$this->compile($conditional_buff,$result);
			unset($conditional_buff);
		    $i++;
		  }
		}	
	}

	// While function
	function make_while($buff, &$buff){
		if(preg_match('/<!--while\((.*)\)-->(\n+)(.*+)(\n+)<!--endwhile-->/', $buff, $matches)){
			$wbuff;
			while($matches[1]){
				$wbuff .= $matches[3];
			}
 			$buff = str_replace($matches[0], $wbuff, $buff);
		}
	}
	// Foreach function
	function make_foreach($buff, &$buff){
		if(preg_match_all('|<!--foreach\((.+)\)-->(\s+)(.+)(\s+)<!--endforeach-->|Uis', $buff, $matches, PREG_SET_ORDER)){
		  foreach($matches as $match){
			  $conditions = explode("as", $match[1]);
			  $first = eval("return $conditions[0];");
			  $fbuff = null;
			  foreach($first as $second){
				  $fcompile = $match[3];
				  if(preg_match_all('|{=item\((.+)\)}|Uis', $match[3], $fmatches, PREG_SET_ORDER)){
					  foreach($fmatches as $fmatch){
						if($second[$fmatch[1]]){
						  $fcompile = str_replace($fmatch[0], $second[$fmatch[1]], $fcompile);
						}
					  }
				  }
				  $fbuff .= $fcompile;
			  }
			  $buff = str_replace($match[0], $fbuff, $buff);
			  unset($fbuff);
		    }
		}
	}

	// Menu function
	function make_menus($buff, &$buff){
		if(preg_match('/<!--menu\((.+)\)-->(\s+)(.+)(\s+)<!--endmenu-->/', $buff, $matches)){
			$id = (int)$matches[1];
			$this->apploadlib(KLEO_LIB_DIR.'menus.lib.php', "kleomenu", $menu);
			$menu->load_menu($id, $menu_items);
			$mbuff = null;
			$i=0;
			foreach($menu_items['items'] as $menu_item){
				$mbuff .= $matches[3];
				if(!isset($menu_item['childs'])){
					$menu_item['childs'] = false;
				}
				$this->tpl_set(array(
						"MENU_ITEM" => $menu_item['title'],
						"MENU_CLASS" => $menu_item['class'],
						"MENU_LINK" => $menu_item['link'],
						"MENU_ICON" => $menu_item['icon'],
						"ITEM_ID" => $menu_item['mitid'],
						"i" => $i,
						"MENU_ITEM_CHILDS" => $menu_item['childs']
					), 
					false, $mbuff, $mbuff);
			}
			$i++;
 			$buff = str_replace($matches[0], $mbuff, $buff);
		}
	}

	function make_menuchilds($buff, &$buff){
		if(preg_match('/<!--menuchilds\((.+)\)-->(\s+)(.+)(\s+)<!--endmenuchilds-->/', $buff, $matches)){
			$cuts = explode(",",$matches[1]);
			$id = (int)$cuts[0];
			$parent = (int)$cuts[1];
			$this->apploadlib(KLEO_LIB_DIR.'menus.lib.php', "kleomenu", $menu);
			$menu->load_menu($id, $menu_child_items, $parent);
			$mcbuff;
			foreach($menu_child_items['items'] as $menu_child_item){
				$mcbuff .= $matches[3];
				$this->tpl_set(array(
						"MENU_CHILD_ITEM" => $menu_child_item['title'],
						"MENU_CHILD_CLASS" => $menu_child_item['class'],
						"MENU_CHILD_LINK" => $menu_child_item['link'],
					), 
					false, $mcbuff, $mcbuff);
			}
 			$buff = str_replace($matches[0], $mcbuff, $buff);
		}

	}

	// Eval function
	function make_eval($buff, &$buff){
		$buff = preg_replace_callback('/\{=eval\(([\S\-]+)\)\}/', create_function('$eval', 'return eval("return $eval[1];");'), $buff);
	}

	// A cool function: i think i did this just for fun but it's coooool and you can see the structure of a template function perfectly from here :-)
	function howmanyletters($buff, &$buff){
		if(preg_match('/\{=howmanyletters\((.*)\)\}/', $buff, $matches)){
			$howmany = strlen($matches[1]);
			$buff = preg_replace('/\{=howmanyletters\((.*)\)\}/', $howmany, $buff);
		}

	}
	// P.D: If you not understand the gist of the function, it just return the count of letters from a word (yes, i know, it suks :-P)


	// Include function
	function make_includes($buff, &$buff){
		// The regex... (hacerla con callback me costó un huevo y medio)
		if(preg_match('/\{=include\((.*)\)\}/', $buff, $matches)){
		if(file_exists($matches[1])){
			$buff = preg_replace_callback('/\{=include\((.*)\)\}/', create_function('$file', 'return file_get_contents($file[1]);'), $buff);
		} else if(file_exists(KLEO_FULL_TEMPLATE_ROUTE.$matches[1])) {
			$buff = preg_replace_callback('/\{=include\((.*)\)\}/', create_function('$file', 'return file_get_contents(KLEO_FULL_TEMPLATE_ROUTE.$file[1]);'), $buff);
		} else if(file_exists(KLEO_ACTUAL_MODULE.'/views/'.$matches[1])){
			$buff = preg_replace_callback('/\{=include\((.*)\)\}/', create_function('$file', 'return file_get_contents(KLEO_ACTUAL_MODULE.\'/views/\'.$file[1]);'), $buff);
		} else {
			$this->apperror($matches[1].' <-- not exists '.L_TEMPLATE_ERROR, 'common');
		}
}
	}
	// Icons functions
	function make_icons($buff, &$buff){

		if(preg_match('/\{=icon\((.*),(.*),(.*)\)\}/', $buff, $matches)){
			var_dump($matches);
		}

	}
	// Lang
	function make_lang($buff, &$buff){

/*		preg_match_all('/\{=lang\(([\w\-]+)\)\}/', $buff, $m);
		foreach ($m[1] as $value) 

		if(!defined($value)){
				$this->apperror($value." Is not a constant", "common");
		}

		$buff = str_replace('{=lang('.$value.')}', constant($value), $buff);
*/
		$buff = preg_replace_callback('/\{=lang\(([\w\-]+)\)\}/', create_function('$constant', 'return constant($constant[1]);'), $buff);
	}
	// Call to defines
	function make_constants($buff, &$buff){
		$buff = preg_replace_callback('/\{=const\(([\w\-]+)\)\}/', create_function('$constant', 'return constant($constant[1]);'), $buff);
	}

	// Call to core functions
	function make_core($buff,&$buff){
		if(preg_match('/\{=core\((.+)\)\}/', $buff, $matches)){
			$buff = str_replace('{=core('.$matches[1].')}', $this->get_core_value($matches[1]), $buff);
		}
	}
	/* 
	 * It's the turn of the custom fields
	 * (Ya, wordpress is not the only CMS that has it ¬¬)
	 * Just a pair of crazy functions to work it out
	 */
	function make_custom_fields($buff,&$buff){
		if(preg_match('/\{=custom\((.+)\)\}/', $buff, $matches)){
			$buff = str_replace('{=custom('.$matches[1].')}', $this->call_custom_field($matches[1]), $buff);
		}
	}
	function call_custom_field($name){
		if(!empty($this->post_id)){
			$query = $this->query("SELECT * FROM ".KLEO_TABLE_PREFIX."conf WHERE reference = $this->post_id AND name = '$name' AND status = 1");
			$row = $this->fetch_array($query);
			return utf8_encode($row['value']);
		} else {
			return false;
		}
	}
	/* This could be something like 'template custom fields' but you must declare it as a variable inside the class 'template_konf' in a file called konf.php at your tpl directory (sounds like tongue-twister :-P). The unique difference between template custom fields and the conventional fields is that this one does not require any database connection. */
	function make_template_variables($buff, &$buff){
		if(file_exists(KLEO_FULL_TEMPLATE_ROUTE.'konf.php')){
			$this->apploadlib(KLEO_FULL_TEMPLATE_ROUTE.'konf.php', "template_konf", $template);
			if(preg_match('/\{=template\((.+)\)\}/', $buff, $matches)){
				$buff = preg_replace('/\{=template\((.+)\)\}/', $template->konf[$matches[1]], $buff);
			}
		} else {
			return false;
		}
	}

	function make_get($buff,&$buff){
		$buff = preg_replace_callback('/\{=get\((.+)\)\}/', create_function('$c', 'return $_GET[$c[1]];'), $buff);
	}

	function make_sidebar_calls($buff,&$buff, &$output){
		if(preg_match('/\{=sidebar\((.+)\)\}/', $buff, $matches)){

			$cuts = explode(",",$matches[1]);

			foreach($cuts as $cut){
				$output[] = $cut;
			}
			$buff = str_replace($matches[0], null, $buff);
		}

	}

	function make_breadcumbs($buff,&$buff,&$output){
		if(preg_match('/\{=breadcrumbs\((.+)\)\}/', $buff, $matches)){
			$output = $matches[1];
			$buff = str_replace($matches[0], null, $buff);
		}

	}

	function make_admin_caption($buff,&$buff,&$output){
		if(preg_match('/\{=caption\((.+)\)\}/', $buff, $matches)){
			$output = $matches[1];
			$buff = str_replace($matches[0],null,$buff);
		}
	}

	function make_date($buff,&$buff){
		if(preg_match('/\{=date\((.+)\)\}/', $buff, $matches)){
			$buff = str_replace($matches[0],eval('return $this->the_date($matches[1]);'),$buff);
		}
	}

	function set_title($title, $buff, &$buff){
		$buff = preg_replace('/\<title\>(.+)<\/title\>/', '<title>'.$title.'</title>', $buff);
	}
	function search_tpl($file,&$path,$search=false){
		if(file_exists($file)){
			$path = $file;
		} else if(file_exists(KLEO_FULL_TEMPLATE_ROUTE.$file)) {
			$path = KLEO_FULL_TEMPLATE_ROUTE.$file;
		} else if(file_exists(KLEO_FULL_TEMPLATE_ROUTE.$search.'/'.$file)) {
			$path = KLEO_FULL_TEMPLATE_ROUTE.$search.'/'.$file;
		} else if(file_exists(KLEO_FULL_TEMPLATE_ROUTE.'/'.KLEO_ACTUAL_MODULE.'/'.$file)) {
			$path = KLEO_FULL_TEMPLATE_ROUTE.'/'.KLEO_ACTUAL_MODULE.'/'.$file;
		} else if(file_exists(KLEO_MODULES_DIR.KLEO_ACTUAL_MODULE.'/views/'.$file)){
			$path = KLEO_MODULES_DIR.KLEO_ACTUAL_MODULE.'/views/'.$file;
		} else if(file_exists(KLEO_MODULES_DIR.$search.'/views/'.$file)){
			$path = KLEO_MODULES_DIR.$search.'/views/'.$file;
		} else if(file_exists(KLEO_MODULES_DIR.$file)){
			$path = KLEO_MODULES_DIR.$file;
		}
	}
	// And the moment of the truth... 
	function compile($buff, &$buff){
		if(isset($_SESSION['postid'])){
			$this->post_id = $_SESSION['postid'];
		} else {
			$this->post_id = false;
		}
		// {=const
		$this->make_constants($buff, $buff);
		// Replace the <!--if()--> clauses
		$this->make_conditionals($buff, $buff);
		// <!--While
		$this->make_while($buff, $buff);
		// <!--foreach
		$this->make_foreach($buff, $buff);
		// <!--menu
		$this->make_menus($buff, $buff);
		// <!--menuchilds
		$this->make_menuchilds($buff, $buff);
		// {=eval(
		$this->make_eval($buff, $buff);
		// {=get(
		$this->make_get($buff, $buff);
		// {=link
		$this->make_links($buff, $buff);
		// {=icon
		$this->make_icons($buff, $buff);
		// {=howmanyletters
// 		$this->howmanyletters($buff, $buff);
		// {=lang
		$this->make_lang($buff, $buff);
		// {=core
		$this->make_core($buff, $buff);
		// {=date
		$this->make_date($buff, $buff);
		// {=template
		$this->make_template_variables($buff, $buff);
		// Custom fields
		if(!empty($this->post_id)){
			$this->make_custom_fields($buff,$buff);
		}
	}

}
?>
